package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jsola.file.vo.BankCardInfoVO;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.provider.IFileProviderService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.IEmpSocInfoService;
import org.jsola.hr.service.IFlushedBackCard;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author lyh
 */
@Service("hrFlushedBackCardImpl")
@Slf4j
public class FlushedBackCardImpl implements IFlushedBackCard {

    @Autowired
    private IEmpInfoService empInfoService;

    @Autowired
    private IFileProviderService fileProviderService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void flushedBackCard(TokenUser tokenUser) {
        List<EmpInfoDO> empList = empInfoService.selectSiteEmp(tokenUser);
        for (EmpInfoDO empInfo : empList) {
            String annexSalaryCard = empInfo.getAnnexSalaryCard();
            if(!StringUtils.isEmpty(annexSalaryCard)){
                List<String> salaryCardList = Arrays.asList(annexSalaryCard.split(","));
                Collections.reverse(salaryCardList);
                String currentSalaryCardUrl = salaryCardList.get(0);
                try {
                    BankCardInfoVO bankcard = fileProviderService.bankcard(currentSalaryCardUrl, tokenUser);
                    if (Objects.equals(0, bankcard.getBankCardType())) {
                        continue;
                    }
                    String bankName = bankcard.getBankName();
                    String bankCardNumber = bankcard.getBankCardNumber() == null ? bankcard.getBankCardNumber()
                            : bankcard.getBankCardNumber().replaceAll(" ", "");
                    empInfo.setBankCard(bankCardNumber);
                    empInfo.setBankName(bankName);
                    empInfoService.updateByIdSelective(empInfo);
                } catch (Exception e){
                    log.error("员工{}刷新银行卡失败,报错信息{}",empInfo.getName(),e.getMessage());
                }
            }
        }
    }
}
